import React, { PureComponent } from 'react'
import { View, ScrollView, Text } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { getThemeStyle, timestampToTime } from '@/utils'
import { ORDER_LIST_CANCEL_REASON } from '@/consts'
import { withPager, withBackToTop } from '@/hocs'
import { SpLoading, SpNote, SpTab, SpToast, SpNavBar, CouponItem } from '@/components'
import { CommonButton } from '@/components/sp-page-components'
import { calculateTimestamp } from '@/utils/time'
import { classNames } from '@/utils'
import api from '@/api'
import { connect } from 'react-redux'
import './index.scss'
import S from '@/spx'
import { Tracker } from '@/service'
import { PullToRefresh, InfiniteScroll, Modal, Radio, Space, Form, Stepper, Image } from 'antd-mobile'
import imageDown from './downloadImage'

const TAB_LIST = [
  { value: '2', label: '已生效' },
  { value: '1', label: '待失效' },
  { value: '3', label: '已过期' },
]
const ACTION_LIST = [
  { label: '删除', plain: true, type: 'delete' },
  { label: '编辑库存', plain: true, type: 'edit' },
  { label: '投放', type: 'onsale' }
]

@connect(({ planSelection }) => ({
  planSelection: planSelection.activeShop
}))
@withPager
@withBackToTop


export default class List extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      activeIndex: 2,
      actionType: '',
      orderList: [],
      loading: false,
      stepValue: 0,
      radioValue: 'increase',
      couponType: 'discount',
    }
  }


  searchFilter = async ({ isCMD, isResetList, isFirst }) => {
    let query = {}
    if (isFirst) {
      return
    }
    if (isCMD) {
      //如果是初始化
      query.orderList = []
      query.inputValue = ''
    }

    if (isResetList) {
      //筛选时需要置空
      query.orderList = []
    }
    // this.state.Bscroll.scrollTo(0,0,300)
    this.resetPage(() => {
      this.setState(
        {
          ...this.state,
          ...query
        },
        () => {
          this.nextPage()
        }
      )
    })

  }



  //获取订单列表
  getOrdersList = async (params) => {

    const {
      list,
      pagers: { total: total }
    } = await api.coupon.couponList({
      page_no: params.page_no,
      page_size: params.page_size,
      date_status: this.state.activeIndex,
      store_self: false,
    })

    this.setState({
      orderList: params.page_no > 1 ? [...this.state.orderList, ...list] : list
    })
    return {
      total
    }
  }

  //请求
  fetch = async (params) => {
    this.setState({
      loading: true
    })
    console.log('-----fetch-----', params)
    const { total } = await this.getOrdersList(params)

    this.setState({
      loading: false
    })

    return { total }
  }


  handleRefresh = () => {
    this.searchFilter({ isResetList: true })
  }

  //点击商品列表
  handleClickGoodItem = (info) => {
    Taro.navigateTo({ url: `/pages/coupon/detail?card_id=${info.card_id}` })
  }

  navigateToGoodForm = () => {

    const { stepValue, couponType } = this.state
    Modal.confirm({
      //   title: '选择优惠券类型',
      header: '修改库存数',
      title: (
        <Radio.Group defaultValue={couponType} onChange={(e) => {
          this.setState({ couponType: e })
        }}>
          <Space direction='vertical' align='center' justify='center'>
            <Radio value='discount'>折扣券</Radio>
            <Radio value='cash'>满减券</Radio>
            {/* <Radio value='new_gift'>兑换券</Radio> */}
          </Space>
        </Radio.Group>
      ),
      showCloseButton: true,
      onConfirm: async () => {
        console.log('Confirmed')
        Taro.navigateTo({ url: `/pages/coupon/creat?type=${this.state.couponType}` })
      },
      confirmText: '创建',
      closeOnAction: true,
    })
  }
  //点击tab
  handleChangeTab =  (active) => {
    console.log('点击了tab', TAB_LIST[active].value)
    this.setState({
      activeIndex: TAB_LIST[active].value
    }, async () => {
      await this.searchFilter({ isResetList: true })
    })

  }
  //编辑
  editCoupon = async (info) => {
   this.setState({ radioValue: 'increase', stepValue: 0 })
    const { stepValue, radioValue } = this.state
    Modal.show({
      title: (
        <div>
          <Radio.Group defaultValue={radioValue} onChange={(e) => {
            this.setState({ radioValue: e })
          }}>
            <Space direction='horizontal'>
              <Radio value='increase'>增加</Radio>
              <Radio value='reduce'>减少</Radio>
            </Space>
          </Radio.Group>
        </div>
      ),
      header: '修改库存数',
      content: (
        <>
          <Form layout='horizontal'>
            <Form.Item name='amount' label='数量' childElementPosition='right'>
              <Stepper min={0} max={this.state.radioValue == 'reduce' ? (info.quantity - info.get_num) : '999999999999'} value={stepValue} onChange={(e) => { this.setState({ stepValue: e }) }} />
            </Form.Item>
          </Form>
        </>
      ),
      showCloseButton: true,
      actions: [
        {
          key: 'online',
          text: '修改',
          primary: true,
          onClick: async () => {
            if (this.state.radioValue == 'reduce') {
              if (this.state.stepValue > (info.quantity - info.get_num)) {
                Taro.showToast({
                  title: '减少数量不能大于可领取库存',
                  icon: 'none'
                })
                return
              }
            }
            await api.coupon.updateStore({ type: this.state.radioValue, quantity: this.state.stepValue, card_id: info.card_id })
            this.searchFilter(false)

          }
        }
      ],
      closeOnAction: true,
    })
  }
  // 投放
  toufangCoupon = async (info) => {
    Taro.showLoading('加载中...')
    let appCodeUrl = ''
    const page = 'https://h5.mimijishi.com/subpages/marketing/coupon-center'
    this.curPageUrl = `${page}?card_id=${info.card_id}`
    let params = {
      wxaAppId: 'wxb9a69be6d8017b9a',
      page: 'subpages/marketing/coupon-center',
      card_id: info.card_id
    }
    const data = await api.coupon.getPageCode(params)
    appCodeUrl = data.base64Image
    Taro.hideLoading()
    Modal.alert({
      title: '投放二维码',
      content: (
        <Image class="page-code" src={appCodeUrl}></Image >
      ),
      showCloseButton: true,
      onConfirm: async () => {
        console.log('Confirmed')
        await imageDown(appCodeUrl)
        Taro.showToast({
          title: '已保存到相册',
          icon: 'none'
        })
      },
      confirmText: '保存到相册'
      // https://h5.mimijishi.com/subpages/marketing/coupon-center?card_id=18
    })
  }
  // 点击操作按钮
  handleAction = async (info, { type, label }, e) => {
    console.log(e)
    if (type === 'edit') {
      // navigateToGoodForm(info.goods_id)
      this.editCoupon(info)
    } else if (type === 'delete') {
      const { confirm } = await Taro.showModal({
        title: '删除优惠券',
        content: '确定要删除？'
      })
      if (confirm) {
        Taro.showToast({
          title: '删除中...',
          icon: 'none'
        })
        await api.coupon.deleteCoupon(info.card_id)
        await this.searchFilter({ isResetList: false })
      }
    } else {
      //投放
      this.toufangCoupon(info)
    }
  }
  async componentWillUnmount() {
    console.log('2222')

  }
  componentDidMount() {

  }

  async componentDidShow() {
    console.log('dianwu h5 comonentDidShow...')
    await this.searchFilter({ isCMD: true, isFirst: false })
  }

  onPullDownRefresh = async () => {
    // Tracker.dispatch('PAGE_PULL_DOWN_REFRESH')
    await this.searchFilter({ isResetList: false })

  }

  render() {
    const {
      orderList,
      page,
      buttonsActionVisible
    } = this.state
    const statusRecord = {
      pulling: '用力拉',
      canRelease: '松开吧',
      refreshing: '玩命加载中...',
      complete: '好啦',
    }
    return (
      <View>
        <SpNavBar title='优惠券' />
        <View className='page-order-list' style={getThemeStyle()}>
          <View className='header'>
            <SpTab dataSource={TAB_LIST} onChange={this.handleChangeTab} />
          </View>

          <PullToRefresh
            onRefresh={this.onPullDownRefresh}
            renderText={status => {
              return <div>{statusRecord[status]}</div>
            }}
          >
            <ScrollView
              scrollY
              className={classNames('wrapper', 'page-order-list-orderList', {
                ['show-buttonsaction']: buttonsActionVisible
              })}
              scrollWithAnimation
            // onScrollToLower={this.nextPage}
            // onScrollToUpper={this.onPullDownRefresh}
            >
              <View className='content' >
                {orderList.map((item, index) => {
                  // const buttons = orderItem?.app_info?.buttons.filter((btn) => btn.type != 'markdown' && btn.type != 'invoice')
                  let actions = ACTION_LIST
                  return (
                    <CouponItem info={item} key={item.card_id}
                      onClick={() => { this.handleClickGoodItem(item) }}
                      renderFooter={
                        <View>
                          {actions.map((item2, index2) => {
                            return (
                              <CommonButton
                                text={item2.label}
                                size='small'
                                type={item2.type === 'delete' ? 'danger' : 'primary'}
                                plain={item2.plain}
                                key={index2}
                                className='common-button'
                                onClick={(e) => {
                                  e.stopPropagation()
                                  this.handleAction(item, item2)
                                }}
                              />
                            )
                          })}
                        </View>
                      }
                      renderLeft={
                        <View>
                          <Text style="display:inline-block;padding-right: 12px;color:#679BDD ;">使用概况:{item.use_num}/{item.get_num}</Text>
                          {/* <Text style="color:#679BDD ;">使用量:{item.use_num}</Text> */}
                          <View style="color:#21b991">可领取库存:{item.quantity - item.get_num}</View>
                        </View>}
                    >
                      <View
                        style={{ fontSize: '22rpx' }}
                      // onClick={this.handleClickNews.bind(this, item, idx)}
                      >
                        去查看
                      </View>

                    </CouponItem>
                  )
                })}
                <InfiniteScroll loadMore={this.nextPage} hasMore={page.hasNext} />
                {/* {loading && <SpLoading>正在加载...</SpLoading>} */}

                {!page.isLoading && !page.hasNext && !orderList.length && (
                  <SpNote img='no_order.png'>暂时还没有此类优惠券</SpNote>
                )}

                {/* {!page.hasNext && !!orderList.length && <SpTips msg={'没有更多了哦~'}></SpTips>} */}
              </View>
            </ScrollView>
          </PullToRefresh>
          <View className='page-order-list-addbutton'>
            {/* <View className='iconfont icon-tianjia'></View> */}
            <View className='text' onClick={() =>
              this.navigateToGoodForm()}>
              创建优惠券
            </View>
          </View>
        </View>
      </View>

    )
  }
}
